﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Direct.Modularity;
using Direct.Logging;
using System.IO;
using Direct.Core;
using Direct.Security;

namespace Direct.Bootstrap
{
    [ModuleCategory(ModuleCategory.Core)]
    [ModulePriority(ModulePriority.Higher)]
    [ModuleDescription("Núcleo do servidor")]
    public class CoreModule : IModule
    {
        public void Initialize()
        {
            RegisterSystemAuthKeys();
        }

        public void Run()
        {
            CheckSystemUser();
            ServiceLocator.GetInstance<ILogManager>()
                .GetSystemLogger()
                .Log("Core module inicialized", Category.Info, Priority.None);
        }

        private void RegisterSystemAuthKeys()
        {
            var authService = ServiceLocator.GetInstance<IAuthorizationService>();
            authService.CreateKey(SystemAuthKeys.Security.Root, "Gerenciar permissões de acesso");
            authService.CreateKey(SystemAuthKeys.Security.EditSchemas, "Criar e editar esquemas de usuário");
            authService.CreateKey(SystemAuthKeys.Security.EditRoles, "Criar e editar papéis de usuário");
            authService.CreateKey(SystemAuthKeys.Security.EditUsers, "Criar e editar usuários");
            authService.CreateKey(SystemAuthKeys.Security.EditAttributes, "Editar atributos de usuários e esquemas", 1);
            authService.CreateKey(SystemAuthKeys.Security.EditDefaultPermissions, "Alterar permissões padrão");
        }

        private void CheckSystemUser()
        {
            var accountService = ServiceLocator.GetInstance<IAccountService>();

            var schema = accountService.GetSchema("system_users");

            if (schema == null)
                schema = accountService.CreateSchema("system_users", "Usuários do sistema", "Esquema de usuários administradores do sistema");

            //depois o role
            var role = accountService.GetRole("Administrators");
            if (role == null)
                role = accountService.CreateRole("Administrators", "Sistema", "Funções principais dos administradores de sistema");

            if (!role.IsInSchema(schema))
                schema.AddRole(role);

            var sysUser = accountService.GetUser("system");
            if (sysUser == null)
                sysUser = accountService.CreateUser(schema, "system", "Administrador", "marcelo@mdzn.net", "Usuário raiz do sistema");
            if (sysUser.PasswordHash.IsEmpty())
            {
                accountService.SetUserPassword(sysUser, "system");
            }

            if (!sysUser.IsInRole(role))
                role.AddUser(sysUser);
        }
    }
}
